<?php


class Events extends Controller {

	function Events()
	{
		parent::Controller();
		
		if(! $this->dx_auth->is_logged_in()	){
			redirect('/auth/login/', 'refresh');
		}
		
		$this->load->library('form_validation');

		$this->load->model('ElectionEvent','elEvent');
		$this->load->model('Positions','position');
	}
	
	function index(){
	
		
		$var['allEvents'] = $this->elEvent->get_all();
		$var['title_for_layout'] = "Election Events";
		$this->layout->view('events/index',$var);
		
		
	}
	
	function show($name,$id){

		$qry = $this->elEvent->get_event_by_id($id);
		$qryArr = $qry->row_array();
		$var['event_id'] = $qryArr['id'];
		$var['event_name'] = $qryArr['event_name'];
		$var['event_info'] = $qryArr['event_info'];
		$var['event_date'] = $qryArr['event_start'];
		$var['status'] = $qryArr['event_enable'];
		
		$qry2 = $this->position->get_all_of_event($id);
		$var['qryNum'] = $qry2->num_rows();
		
		if($var['qryNum'] <= 0){
			$var['result_msg'] = "No positions";
		}else{
			$var['result_msg'] = "Showing ".$qry2->num_rows()." positions";
		}
		
		$var['posArr'] = $qry2;
		
		
		$var['title_for_layout'] = "Election Event - ".$qryArr['event_name'];
		$this->layout->view('events/show',$var);
			
	}
	
	function newEvent(){
	
		$this->form_validation->set_rules('event_name','Event name','required|max_length[45]');			
		$this->form_validation->set_rules('event_info','Event info','required|max_length[100]');			
		$this->form_validation->set_rules('event_enable','Event_enable','max_length[1]');
			
		$this->form_validation->set_error_delimiters('<br /><p class="alert">', '</p>');
	
		if ($this->form_validation->run() == FALSE) // validation hasn'\t been passed
		{
			$var['title_for_layout'] = "New Election Event";
			$this->layout->view('events/new', $var);
		}
		else // passed validation proceed to post success logic
		{
		 	// build array for the model
			
			$form_data = array(
					       	'event_name' => set_value('event_name'),
					       	'event_info' => set_value('event_info'),
					       	'event_enable' => set_value('event_enable')
						);
					
			// run insert model to write data to db
		
			if ($this->elEvent->saveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
			{
				redirect('events/index');   // or whatever logic needs to occur
			}
			else
			{
				echo 'An error occurred saving your information. Please try again later';
			// Or whatever error handling is necessary
			}
		}
			
	}
	

}	

?>